﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceCS.Img2Bytes
{
    public class Core
    {
        /// <summary>
        /// 把图片流转换文本为十六进制的字节字符串
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string ConvertImgToBytesTextHex(Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            using (var br = new BinaryReader(stream))
            {
                var bArr = br.ReadBytes((int)stream.Length);
                var sArr = bArr.Select(b =>
                {
                    var s = Convert.ToString(b, 16).ToUpper();
                    s = s.Length == 1 ? s = "0" + s : s;
                    return s;
                }).ToList();
                var str = string.Join("", sArr);
                return str;
            }
        }
        /// <summary>
        /// 把十六进制的字节字符串转换为图片流
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static Stream ConvertBytesTextHexToImg(string text)
        {
            if (text.Length == 0)
            {
                return new MemoryStream();
            }
            var list = new List<byte>(text.Length / 2);
            for (int i = 0; i < text.Length; i += 2)
            {
                var text1 = text.Substring(i, 2);
                var b = Convert.ToByte(text1, 16);
                list.Add(b);
            }
            var ms = new MemoryStream(list.ToArray());
            return ms;
        }
    }
}
